package com.atguigu.system.controller;

import com.atguigu.common.result.Result;
import com.atguigu.common.util.MD5;
import com.atguigu.model.system.SysUser;
import com.atguigu.model.vo.SysUserQueryVo;
import com.atguigu.system.service.SysUserService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Api(tags = "用户管理")
@RestController
@RequestMapping("/admin/system/sysUser")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    @ApiOperation("分页及带条件查询的方法")
    @GetMapping("/{current}/{size}")
    public Result findPage(@PathVariable Long current , @PathVariable Long size , SysUserQueryVo userQueryVo){
        //创建Page对象
        Page<SysUser> page = new Page<>(current, size);
        //调用SysUserService中分页及带条件查询的方法
        IPage<SysUser> iPage = sysUserService.findPage(page,userQueryVo);
        return Result.ok(iPage);
    }

    @ApiOperation("添加用户")
    @PostMapping("/save")
    public Result save(@RequestBody SysUser sysUser){
        //使用MD5对密码进行加密
        sysUser.setPassword(MD5.encrypt(sysUser.getPassword()));
        //调用SysUserService中保存的方法
        sysUserService.save(sysUser);
        return Result.ok();
    }

    @ApiOperation("删除用户")
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Long id){
        //调用SysUserService中删除的方法
        sysUserService.removeById(id);
        return Result.ok();
    }

    @ApiOperation("根据id查询用户")
    @GetMapping("/getById/{id}")
    public Result getById(@PathVariable Long id){
        //调用SysUserService中根据id查询的方法
        SysUser sysUser = sysUserService.getById(id);
        return Result.ok(sysUser);
    }

    @ApiOperation("更新用户")
    @PutMapping("/update")
    public Result update(@RequestBody SysUser sysUser){
        //设置更新日期
        sysUser.setUpdateTime(null);
        //调用SysUserService中根据用户的方法
        sysUserService.updateById(sysUser);
        return Result.ok();
    }

    @ApiOperation("更新用户状态")
    @GetMapping("/updateStatus/{id}/{status}")
    public Result updateStatus(@PathVariable Long id , @PathVariable Integer status){
        //调用SysUserService中更新用户状态的方法
        sysUserService.updateStatus(id,status);
        return Result.ok();
    }
}
